from pydub import AudioSegment
import os
from pydub.utils import which

# 确保 pydub 能找到 ffmpeg
# AudioSegment.converter = "D:/ffmpeg/bin/ffmpeg.exe"
# AudioSegment.ffprobe = "D:/ffmpeg/bin/ffprobe.exe"

def kgm_to_mp3(kgm_file_path, mp3_file_path):
    # Temporary file paths
    wav_file_path = kgm_file_path.replace('.kgm', '.wav')

    # Decrypt the .kgm file to .wav file
    decrypt_kgm_to_wav(kgm_file_path, wav_file_path)

    # Convert .wav to .mp3
    sound = AudioSegment.from_wav(wav_file_path)
    sound.export(mp3_file_path, format="mp3")

    # Clean up temporary .wav file
    os.remove(wav_file_path)
    print(f"Converted {kgm_file_path} to {mp3_file_path}")


def decrypt_kgm_to_wav(kgm_file_path, wav_file_path):
    # This is a placeholder function. You need to implement the decryption
    # logic specific to .kgm files here.
    # For demonstration, let's assume the decrypted content is directly
    # written to a .wav file.
    with open(kgm_file_path, 'rb') as f_in:
        with open(wav_file_path, 'wb') as f_out:
            # Read the .kgm file and write directly to .wav
            # Implement your actual decryption logic here
            f_out.write(f_in.read())
    print(f"Decrypted {kgm_file_path} to {wav_file_path}")


if __name__ == "__main__":
    print(which("ffmpeg"))
    kgm_file_path = 'D:/KuGou/2/1.kgm'
    mp3_file_path = 'D:/KuGou/2/1.mp3'
    kgm_to_mp3(kgm_file_path, mp3_file_path)
